<template>
  <div class="user-management">
    <h2 style="margin-bottom: 20px;">用户管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchForm.nickname"
            placeholder="请输入用户昵称"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="会员状态">
          <el-select
            v-model="searchForm.is_member"
            placeholder="请选择会员状态"
            clearable
            style="width: 150px;"
          >
            <el-option label="会员" :value="true" />
            <el-option label="普通用户" :value="false" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getUsers">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="table-actions">
      <div class="actions-left">
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>
    
    <!-- 用户表格 -->
    <div class="content-card">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <div class="user-avatar">
                <img v-if="scope.row.avatar_url" :src="scope.row.avatar_url" alt="头像" />
                <el-icon v-else><User /></el-icon>
              </div>
              <div class="user-details">
                <div class="user-name">{{ scope.row.nickname || '未设置' }}</div>
                <div class="user-phone">{{ scope.row.phone || '未绑定' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="会员信息" min-width="120">
          <template #default="scope">
            <el-tag :type="scope.row.is_member ? 'success' : 'info'">
              {{ scope.row.is_member ? scope.row.member_level : '普通用户' }}
            </el-tag>
            <div v-if="scope.row.is_member && scope.row.member_expire_date" class="member-expire">
              到期：{{ formatDate(scope.row.member_expire_date) }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="账户余额" prop="balance" width="100">
          <template #default="scope">
            <span class="balance">¥{{ scope.row.balance }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="累计充值" prop="total_recharge" width="100">
          <template #default="scope">
            ¥{{ scope.row.total_recharge }}
          </template>
        </el-table-column>
        
        <el-table-column label="累计消费" prop="total_consumption" width="100">
          <template #default="scope">
            ¥{{ scope.row.total_consumption }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="viewUser(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getUsers"
          @current-change="getUsers"
        />
      </div>
    </div>
    
    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="userDialog.visible"
      title="用户详情"
      width="600px"
    >
      <div v-if="userDialog.user" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ userDialog.user.id }}
          </el-descriptions-item>
          <el-descriptions-item label="微信OpenID">
            {{ userDialog.user.openid }}
          </el-descriptions-item>
          <el-descriptions-item label="昵称">
            {{ userDialog.user.nickname || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ userDialog.user.phone || '未绑定' }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ getGenderText(userDialog.user.gender) }}
          </el-descriptions-item>
          <el-descriptions-item label="地区">
            {{ getUserLocation(userDialog.user) }}
          </el-descriptions-item>
          <el-descriptions-item label="会员状态">
            <el-tag :type="userDialog.user.is_member ? 'success' : 'info'">
              {{ userDialog.user.is_member ? userDialog.user.member_level : '普通用户' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会员到期">
            {{ userDialog.user.member_expire_date ? formatDate(userDialog.user.member_expire_date) : '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="账户余额">
            <span class="balance">¥{{ userDialog.user.balance }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="累计充值">
            ¥{{ userDialog.user.total_recharge }}
          </el-descriptions-item>
          <el-descriptions-item label="累计消费">
            ¥{{ userDialog.user.total_consumption }}
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDate(userDialog.user.created_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)

// 搜索表单
const searchForm = ref({
  nickname: '',
  phone: '',
  is_member: null
})

// 用户列表
const users = ref([])

// 分页
const pagination = ref({
  page: 1,
  per_page: 20,
  total: 0
})

// 用户详情弹窗
const userDialog = ref({
  visible: false,
  user: null
})

// 获取用户列表
const getUsers = async () => {
  loading.value = true
  try {
    // 模拟数据 - 实际项目中应该调用真实API
    const mockUsers = [
      {
        id: 1,
        openid: 'wx123456789',
        nickname: '张三',
        avatar_url: '',
        phone: '13800138001',
        gender: 1,
        city: '北京',
        province: '北京',
        country: '中国',
        is_member: true,
        member_level: 'VIP',
        member_expire_date: '2025-12-31T23:59:59',
        balance: 299.50,
        total_recharge: 1000.00,
        total_consumption: 700.50,
        status: 1,
        created_at: '2025-01-01T10:00:00'
      },
      {
        id: 2,
        openid: 'wx987654321',
        nickname: '李四',
        avatar_url: '',
        phone: '13800138002',
        gender: 2,
        city: '上海',
        province: '上海',
        country: '中国',
        is_member: false,
        member_level: '普通',
        member_expire_date: null,
        balance: 50.00,
        total_recharge: 200.00,
        total_consumption: 150.00,
        status: 1,
        created_at: '2025-01-15T14:30:00'
      }
    ]
    
    users.value = mockUsers
    pagination.value.total = mockUsers.length
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    nickname: '',
    phone: '',
    is_member: null
  }
  getUsers()
}

// 刷新数据
const handleRefresh = () => {
  getUsers()
}

// 查看用户
const viewUser = (user) => {
  userDialog.value.user = user
  userDialog.value.visible = true
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  const action = user.status === 1 ? '禁用' : '启用'
  
  try {
    await ElMessageBox.confirm(`确定要${action}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    user.status = user.status === 1 ? 0 : 1
    ElMessage.success(`${action}用户成功`)
  } catch (error) {
    // 用户取消操作
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取性别文本
const getGenderText = (gender) => {
  switch (gender) {
    case 1: return '男'
    case 2: return '女'
    default: return '未知'
  }
}

// 获取用户地区信息
const getUserLocation = (user) => {
  const parts = []
  if (user.country) parts.push(user.country)
  if (user.province) parts.push(user.province)
  if (user.city) parts.push(user.city)
  return parts.join(' ') || '未设置'
}

onMounted(() => {
  getUsers()
})
</script>

<style lang="scss" scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .el-icon {
    font-size: 20px;
    color: #999;
  }
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.user-phone {
  font-size: 12px;
  color: #666;
}

.member-expire {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.balance {
  font-weight: 600;
  color: #1890ff;
}

.user-detail {
  .el-descriptions {
    :deep(.el-descriptions__label) {
      width: 120px;
    }
  }
}
</style>